package com.gs.synedocket.util;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.Process;
import android.util.Log;

import androidx.annotation.NonNull;

import com.gs.synedocket.constant.AllConstants;
import com.gs.synedocket.db.dao.LogUtil;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

public class CrashHandler implements Thread.UncaughtExceptionHandler {

    private static final String PATH = Environment.getExternalStorageDirectory().getPath() + "/Android/data/" + AppUtil.getInstance().getContext().getPackageName() + "/crashLog/";
    private static final String FILE_NAME = "crash";
    private static final String FILE_NAME_SUFFIX = ".txt";
    private static volatile CrashHandler instance = new CrashHandler();
    private Thread.UncaughtExceptionHandler mDefaultCrashHandler;

    private CrashHandler() {
    }

    public static CrashHandler getInstance() {
        return instance;
    }

    public void init() {
        mDefaultCrashHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(@NonNull Thread t, @NonNull Throwable e) {
        Log.i(AllConstants.TAG, "catch exception");
        // 导出异常信息到SD卡中
        dumpExceptionToSDCard(e);
        e.printStackTrace();
        if (mDefaultCrashHandler != null) {
            mDefaultCrashHandler.uncaughtException(t, e);
        } else {
            Process.killProcess(Process.myPid());
        }
    }

    private void dumpExceptionToSDCard(Throwable e) {
        File dir = new File(PATH);
        if (!dir.exists()) {
            dir.setReadable(true);
            dir.mkdirs();
        }
        String time = DateUtil.DateTimeToStr(new Date(), "yyyyMMdd_HHmmss");
        File file = new File(PATH + FILE_NAME + time + FILE_NAME_SUFFIX);
        file.setReadable(true);
        PrintWriter pw = null;
        try {
            pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
            pw.println(time);
            dumpPhoneInfo(pw);
            pw.println();
            e.printStackTrace(pw);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (pw != null) {
                pw.close();
            }
        }
        LogUtil.getInstance().insertOrReplaceData("报错：" + e.getMessage());
//        LogUtil.getInstance().insertOrReplaceData("报错：" + Log.getStackTraceString(e));
    }

    private void dumpPhoneInfo(PrintWriter pw) {
        try {
            PackageManager pm = AppUtil.getInstance().getContext().getPackageManager();
            PackageInfo pi = pm.getPackageInfo(AppUtil.getInstance().getContext().getPackageName(), PackageManager.GET_ACTIVITIES);
            pw.print("APP Version:");
            pw.println(pi.versionName);
            pw.print("OS Version:");
            pw.print(Build.VERSION.RELEASE);
            pw.print("_");
            pw.println(Build.VERSION.SDK_INT);
            pw.print("Vendor:");
            pw.println(Build.MANUFACTURER);
            pw.print("Model:");
            pw.println(Build.MODEL);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }
}
